﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sample.Web.Models;
using Sample.Web.Repository;

namespace Sample.Web.Controllers
{
  public class GenreController : Controller
  {
    private readonly IGenreRepository _repo;

    public GenreController(IGenreRepository repo)
    {
      _repo = repo;
    }

    //
    // GET: /Genre/

    public ActionResult Index()
    {
      return View(_repo.GetAll(sort: g => g.OrderByDescending(s => s.GenreId)));
    }

    //
    // GET: /Genre/Details/5

    public ActionResult Details(int id = 0)
    {
      Genre genre = _repo.GetByID(id);
      if (genre == null)
      {
        return HttpNotFound();
      }
      return View(genre);
    }

    //
    // GET: /Genre/Create

    public ActionResult Create()
    {
      return View();
    }

    //
    // POST: /Genre/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Genre genre)
    {
      if (ModelState.IsValid)
      {
        _repo.Create(genre);
        _repo.SaveChanges();
        return RedirectToAction("Index");
      }

      return View(genre);
    }

    //
    // GET: /Genre/Edit/5

    public ActionResult Edit(int id = 0)
    {
      Genre genre = _repo.GetByID(id);
      if (genre == null)
      {
        return HttpNotFound();
      }
      return View(genre);
    }

    //
    // POST: /Genre/Edit/5

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Genre genre)
    {
      if (ModelState.IsValid)
      {
        _repo.Update(genre);
        _repo.SaveChanges();
        return RedirectToAction("Index");
      }
      return View(genre);
    }

    //
    // GET: /Genre/Delete/5

    public ActionResult Delete(int id = 0)
    {
      Genre genre = _repo.GetByID(id);
      if (genre == null)
      {
        return HttpNotFound();
      }
      return View(genre);
    }

    //
    // POST: /Genre/Delete/5

    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
      _repo.Delete(id);
      _repo.SaveChanges();
      return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
      _repo.Dispose();
      base.Dispose(disposing);
    }
  }
}